import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {debounceTime, tap} from 'rxjs/operators';
import {NzMessageService} from 'ng-zorro-antd/message';

@Injectable({
  providedIn: 'root'
})
export class UsedStorePService {
  serviceUrl = {
    deviceList: '/recycleMachine/list', // 机器列表
    deviceDetail: '/recycleMachine/details', // 机器详情
    changeDeviceLocation: '/recycleMachine/update', // 修改库位
    deviceListExport: '/recycleMachine/getOrderExcel', // 机器导出
    channelOccupy: '/recycleMachine/occupy', // 渠道占用
    commodityList: '/recycleGoods/list', // 二手商品列表
    commodityStatus: '/recycleGoods/upDownFrame', // 商品上下架
    commodityUpdate: '/recycleGoods/update', // 商品信息修改
    commodityDetail: '/recycleGoods/details', // 商品详情
    outStoreList: '/recycleDelivery/list', // 出库列表
    outStoreSave: '/recycleDelivery/save', // 出库单保存
    outStoreUpdate: '/recycleDelivery/update', // 出库单修改
    outStoreDetail: '/recycleDelivery/details', // 出库单详情
    outStoreCheck: '/recycleDelivery/deliverGoods', // 更改出库单状态
    cancelSF: '/recycleDelivery/cancel', // 取消顺丰发货
    outStoreLogistics: '/recycleDelivery/updateExpress', // 更改出库单物流信息
    logisticsSF: '/sfOrder/queryPrintInfo', // 顺丰物流信息
    logisticsJD: '/recycleDelivery/jdQueryPrintInfo', // 京东物流信息
    logisticsRecords: '/mallOrderRecord/details', // 快递收发记录
    outStoreTrack: '/recycleFollower/save', // 跟进
    outStoreHistory: '/recycleFollower/list', // 跟进查询
    brandList: '/recycleBrand/list', // 品牌列表
    typeList: '/recycleModel/list', // 机型列表
    track: '/recycleModel/list', // 跟进
    dictUrl: '/dict/detail', // 查询字典
    getAddresser: '/address/get/', // 查询字典
    fileUpload: '/common/upload/file', // 文件上传
    secondUpdateDelayPutUrl: '/recycleGoods/updateDelay', // 二手商品B端延迟上架

    queryModelListUrl: '/recycleModel/list', // 查询机型列表
    goodsAuditUrl: '/recycleGoods/audit', // 商品列表审核
    exportGoodsUrl: '/recycleGoods/getOrderDescExcel', // 商品导出
    exportOutOrderUrl: '/recycleDelivery/getOrderExcel', // 二手出库单导出
    hotSearchList: '/recycleHotWord/list', // 二手热搜新增
    hotSearchAdd: '/recycleHotWord/add', // 二手热搜新增
    hotSearchUpdate: '/recycleHotWord/update', // 二手热搜编辑
    hotSearchMove: '/recycleHotWord/move', // 二手热搜移动
    hotSearchDelete: '/recycleHotWord/delete/', // 二手热搜删除
  };

  constructor(
    private httpClient: HttpClient,
    private message: NzMessageService,
  ) {
  }


  /**
   * 获取品牌
   */
  getAddresser(id: any) {
    return this.httpGet(this.serviceUrl.getAddresser + id, {});
  }

  /**
   * 获取品牌
   */
  getBrandList() {
    return this.httpPost(this.serviceUrl.brandList, {page: 1, pageSize: 9999});
  }


  /**
   * 获取机型
   * @param brandId 品牌id
   */
  getTypeList(brandId: any) {
    return this.httpPost(this.serviceUrl.typeList, {page: 1, pageSize: 9999, brandId});
  }

  /**
   * 获取链接
   */
  getLinkList() {
    return this.httpPost('/mapping/list', {page: 1, pageSize: 99999});
  }


  /**
   * 查询二手热搜
   */
  getHotSearch(body: any) {
    return this.httpPost(this.serviceUrl.hotSearchList, body);
  }

  /**
   * 二手热搜移动1上移2下移
   */
  moveHotSearch(body: any) {
    return this.httpPost(this.serviceUrl.hotSearchMove, body);
  }

  /**
   * 二手热搜删除
   */
  deleteHotSearch(id: any) {
    return this.httpGet(this.serviceUrl.hotSearchDelete + id, {});
  }

  /**
   * 编辑二手热搜
   */
  hotSearchEdit(body: any) {
    const url = body.id ? this.serviceUrl.hotSearchUpdate : this.serviceUrl.hotSearchAdd;
    return this.httpPost(url, body);
  }

  /**
   * 获取机器列表
   * @param code  编码
   * @param status  机器状态 0.正常 1.冻结 2.已出库（多个逗号隔开）
   * @param occupyStatus  渠道占用 0.未占用 1.回收占用 2.商城占用（多个逗号隔开）
   * @param libraryId  库存位置id（多个逗号隔开）
   * @param colourId  成色标识id
   * @param typeId  所属品牌id
   * @param source  所属品牌id
   * @param modelId  所属机型id
   * @param createTime  首次入库时间
   * @param endTime  首次入库结束时间
   * @param beginClinchTime  成交入库开始时间
   * @param endClinchTime  成交入库结束时间
   * @param beginShelvesTime  上架开始时间
   * @param endShelvesTime  上架结束时间
   * @param beginOutBoundTime  出库开始时间
   * @param endOutBoundTime  出库结束时间
   * @param beginAcceptanceTime  验机开始时间
   * @param endAcceptanceTime  验机结束时间
   * @param page 页码
   * @param pageSize 分页大小
   */
  getDevices({
               code = null,
               status = '',
               occupyStatus = '',
               libraryId = '',
               colourId = '',
               typeId = '',
               modelId = '',
               source = null,
               sourceList = [],
               createTime = null,
               endTime = null,
               beginClinchTime = null,
               endClinchTime = null,
               beginShelvesTime = null,
               endShelvesTime = null,
               beginOutBoundTime = null,
               endOutBoundTime = null,
               beginAcceptanceTime = null,
               endAcceptanceTime = null,
               page = 1,
               pageSize = 9999,
             } = {}) {
    return this.httpPost(this.serviceUrl.deviceList, {
      code,
      status,
      occupyStatus,
      libraryId,
      colourId,
      typeId,
      source,
      sourceList,
      modelId,
      createTime,
      endTime,
      beginClinchTime,
      endClinchTime,
      beginShelvesTime,
      endShelvesTime,
      beginOutBoundTime,
      endOutBoundTime,
      beginAcceptanceTime,
      endAcceptanceTime,
      page,
      pageSize,
    });
  }

  /**
   * 机器导出
   */
  devicesExport(params: any) {
    let paramsStr = '';
    for (const [k, v] of Object.entries(params)) {
      if (v) {
        paramsStr += k + '=' + v + '&';
      }
    }
    window.open(this.serviceUrl.deviceListExport + '?' + paramsStr);
  }

  /**
   * 获取机器详情
   * @param  id  机器id
   */
  getDevicesDetail(id: string | number) {
    return this.httpPost(this.serviceUrl.deviceDetail, {id});
  }

  /**
   * 修改库位信息
   * id 机器id
   * libraryId 库位id
   * equipmentCode 机器编码
   */
  changeDeviceLocation(body: any) {
    return this.httpPost(this.serviceUrl.changeDeviceLocation, body);
  }

  /**
   * 获取二手商品列表
   * @param equipmentCode  编码 序列号
   * @param typeId  所属品牌id（多个逗号隔开）
   * @param modelId  所属机型id（多个逗号隔开）
   * @param status（多个逗号隔开）商品状态 0.待上架 1.上架中  2.已售出 3.售后中
   * @param userType（多个逗号隔开）适用用户(0-通用、1-C端、2-B端)
   * @param createTime  开始时间
   * @param colourIdB  B端成色
   * @param colourId  C端成色
   * @param libraryId  库位
   * @param clinchTime  成交入库时间
   * @param clinchEndTime  成交入库时间
   * @param endTime  结束时间
   * @param page 页码
   * @param pageSize 分页大小
   */
  getCommodityList({
                     equipmentCode = '',
                     typeId = '',
                     modelId = '',
                     status = '',
                     userType = '',
                     colourIdB = '',
                     colourId = '',
                     libraryId = '',
                     clinchTime = null,
                     clinchEndTime = null,
                     createTime = null,
                     endTime = null,
                     page = 1,
                     pageSize = 9999,
                   } = {}) {
    return this.httpPost(this.serviceUrl.commodityList, {
      equipmentCode,
      typeId,
      modelId,
      status,
      userType,
      colourIdB,
      colourId,
      libraryId,
      clinchTime,
      clinchEndTime,
      createTime,
      endTime,
      page,
      pageSize,
    });
  }

  /**
   * 获取二手商品详情
   * @param id  商品id
   */
  getCommodityDetail(id: any) {
    return this.httpPost(this.serviceUrl.commodityDetail, {id});
  }

  /**
   * 修改商品信息
   */
  updateCommodity(params: any) {
    return this.httpPost(this.serviceUrl.commodityUpdate, params);
  }

  /**
   * 修改商品状态
   * @param status 商品状态 0.上架中 1.待上架  2.已售出 3.售后中
   * @param id 商品id
   */
  changeCommodityStatus(id: any, status: 0 | 1 | 2 | 3) {
    return this.httpPost(this.serviceUrl.commodityStatus, {
      id,
      status
    });
  }

  /**
   * 渠道占用
   * @param  equipmentCodeList 机器编码（多个用逗号隔开）
   * @param  occupyStatus 渠道占用 0.未占用 1.回收占用 2.商城占用
   */
  channelOccupy(equipmentCodeList: any, occupyStatus: 0 | 1 | 2) {
    return this.httpPost(this.serviceUrl.channelOccupy, {equipmentCodeList, occupyStatus});
  }

  /**
   * 获取出库单列表
   * @param deliveryNumber 出库单号
   * @param isFreight 邮费承担
   * @param beginTime 开始时间
   * @param endTime 结束时间
   * @param deliveryTime 出库开始时间
   * @param endDeliveryTime 出库结束时间
   * @param state 状态(1草稿 2待审核 3待打包 4待出库 5已出库 6已签收 7已取消 8审核不通过 9物流异常)
   * @param type 出库类型
   * @param goods 商品
   * @param orderNum 关联单号
   * @param expressNo 物流号
   * @param page 页码
   * @param pageSize 分页大小
   */
  getOutStoreList({
                    isFreight = '',
                    deliveryNumber = '',
                    beginTime = '',
                    endTime = '',
                    deliveryTime = '',
                    endDeliveryTime = '',
                    state = '',
                    type = '',
                    goods = '',
                    orderNum = '',
                    expressNo = '',
                    page = 1,
                    pageSize = 9999,
                  } = {}) {
    return this.httpPost(this.serviceUrl.outStoreList, {
      isFreight,
      deliveryNumber,
      beginTime,
      endTime,
      deliveryTime,
      endDeliveryTime,
      state,
      type,
      goods,
      orderNum,
      expressNo,
      page,
      pageSize,
    });
  }

  /**
   * 保存出库单
   * @param body 内容
   * @param isUpdate 是否是修改
   */
  outStoreSave(body: any, isUpdate = true) {
    return this.httpPost(isUpdate ? this.serviceUrl.outStoreUpdate : this.serviceUrl.outStoreSave, body);
  }

  /**
   * 获取出库单详情
   * @param id 内容
   */
  outStoreDetail(id: any) {
    return this.httpPost(this.serviceUrl.outStoreDetail, {id});
  }

  /**
   * 出库单状态改变
   * @param ids id
   * @param status 状态 1草稿 2待审核 3待打包 4待出库 5已出库 6已签收 7已取消 8审核不通过 9物流异常
   * @param remark 备注
   * @param deliveryMethod 发货方式(1 顺丰发货 2其他快递 3线下配送)
   * @param expressCode 物流公司唯一编码
   * @param expressNo 快递单号
   * @param expressName 快递公司名称
   */
  outStoreCheck(ids: any, status: any, remark?: any, deliveryMethod?: any, expressCode?: any, expressNo?: any, expressName?: any) {
    return this.httpPost(this.serviceUrl.outStoreCheck, {ids, status, remark, deliveryMethod, expressCode, expressNo, expressName});
  }

  /**
   * 取消顺丰发货
   * @param id id
   */
  cancelSF(id: any) {
    return this.httpPost(this.serviceUrl.cancelSF, {id});
  }

  /**
   * 出库单状态改变
   * @param id id
   * @param deliveryMethod 发货方式(1 顺丰发货 2其他快递 3线下配送)
   * @param expressCode 物流公司唯一编码
   * @param expressNo 快递单号
   * @param isFreight 0我司承担 1用户承担
   * @param freight 快递费
   * @param expressName 物流公司名称
   */
  outStoreLogistics(id: any, deliveryMethod?: any, expressCode?: any, expressNo?: any, isFreight?: any, freight?: any, expressName?: string) {
    return this.httpPost(this.serviceUrl.outStoreLogistics, {id, deliveryMethod, expressCode, expressNo, isFreight, freight, expressName});
  }

  /**
   * 跟进
   * @param body 跟进内容
   */
  outStoreTrack(body: any) {
    return this.httpPost(this.serviceUrl.outStoreTrack, body);
  }

  /**
   * 跟进历史记录
   * @param relationInformation id
   * @param type  1、订单 2、售后 3、客户 4、出库 5直降  6退税 7机器
   * @param modelId  1旧的表示二手回收 2表示二手商城 3表示二手回收
   */
  outStoreHistory(relationInformation: any, type = 4, modelId = 2) {
    return this.httpPost(this.serviceUrl.outStoreHistory, {page: 1, pageSize: 9999, type, modelId, relationInformation});
  }

  /**
   * 京东查询
   * @param waybillNos 物流单号
   * @param id 订单id
   */
  logisticsSF(waybillNos: any, id: any) {
    const body = {id};
    let url = this.serviceUrl.logisticsJD;
    if (waybillNos.match(/sf/i)) {
      Object.assign(body, {waybillNos});
      url = this.serviceUrl.logisticsSF;
    }
    return this.httpGet(url, body);
  }

  /**
   * 京东查询
   * @param type 类型 0全部 1入库  2出库
   * @param operator 操作人
   * @param operateTime 操作时间
   * @param operateEndTime 操作时间
   * @param result 扫码结果
   */
  logisticsRecords(params: any) {
    return this.httpClient.post(this.serviceUrl.logisticsRecords, params).toPromise();
  }

  // 查询渠道（字典）
  dictData(parentKey: any) {
    const params: any = {
      pageNum: 1,
      pageSize: 999,
      parentKey
    };
    return this.httpClient.get(this.serviceUrl.dictUrl, {params}).toPromise();
  }

  // 查询渠道（字典）
  swapListDictData() {
    return this.httpClient.get('/dict/details?key=es_swap_list', {}).toPromise();
  }

  formatTime(date: any, type: 'date' | 'dateTime' | 'time') {
    if (!date || (typeof date) === 'string') {
      return date || '';
    }
    let result = '';
    switch (type) {
      case 'date':
        // @ts-ignore
        result = date.toISOString().match(/\d{4}-\d{2}-\d{2}/)[0];
        break;
      case 'dateTime':
        // @ts-ignore
        result = date.toISOString().match(/\d{4}-\d{2}-\d{2}/)[0] + ' ' + date.toString().match(/\d{2}:\d{2}:\d{2}/)[0];
        break;
      case 'time':
        // @ts-ignore
        result = date.toString().match(/\d{2}:\d{2}:\d{2}/)[0];
        break;
    }
    return result;
  }

  httpGet(url: string, params: any) {
    return this.httpClient.get(url, {params}).pipe(tap((res: any) => {
      if (res.code !== 0) {
        this.message.error(res.message);
      }
    })).toPromise().catch(err => {
      this.message.error(`请求异常${url}`);
    });
  }

  httpPost(url: string, body: any) {
    return this.httpClient.post(url, body).pipe(tap((res: any) => {
      if (res.code !== 0) {
        this.message.error(res.message);
      }
    })).toPromise().catch(err => {
      this.message.error(`请求异常${url}`);
    });
  }


  /**
   * ----------------------------------------------------------------
   * 商品信息添加机器信息
   * ----------------------------------------------------------------
   */

  // 查询机型列表
  queryModelList(params: any) {
    return this.httpClient.post(this.serviceUrl.queryModelListUrl, params).toPromise();
  }

  // 商品列表审核
  goodsAuditDatas(params: any) {
    return this.httpClient.post(this.serviceUrl.goodsAuditUrl, params).toPromise();
  }

  // 商品导出
  exportGoodsData(params: any) {
    return this.httpClient.get(this.serviceUrl.exportGoodsUrl, {params, responseType: 'blob'}).toPromise();
  }

  // 二手出库单导出
  exportOutOrderData(params: any) {
    return this.httpClient.get(this.serviceUrl.exportOutOrderUrl, {params: params}).toPromise();
  }

  /**
   * 二手商品管理修改状态 上架 | 下架
   * 商品状态 0.上架中 1.待上架  2.已售出 3.售后中
   */
  editSecondHandGoodsStatus(params: any) {
    return this.httpClient.post(this.serviceUrl.commodityStatus, params).toPromise();
  }

  /**
   * 二手占用
   * occupyStatus 渠道占用 0.未占用 1.回收占用 2.商城占用
   */
  setSecondHandGoodsOccupy(params: any) {
    return this.httpClient.post(this.serviceUrl.channelOccupy, params).toPromise();
  }

  // 二手商品延迟B端上架
  secondUpdateDelayPutData(params: any) {
    return this.httpClient.post(this.serviceUrl.secondUpdateDelayPutUrl, params).toPromise();
  }
}
